<template>
  <Modal
    title="角色详情"
    size="lg"
    @close="$emit('close')"
  >
    <div class="space-y-6">
      <!-- 基本信息 -->
      <div class="bg-gray-50 rounded-lg p-4">
        <h3 class="text-lg font-medium text-gray-900 mb-4">基本信息</h3>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div class="space-y-3">
            <div class="flex justify-between">
              <span class="text-sm font-medium text-gray-500">角色名称:</span>
              <span class="text-sm text-gray-900 font-medium">{{ role.name }}</span>
            </div>
            <div class="flex justify-between">
              <span class="text-sm font-medium text-gray-500">状态:</span>
              <span
                :class="[
                  'inline-flex items-center px-2 py-1 rounded-full text-xs font-medium',
                  role.status === 'active' 
                    ? 'bg-green-100 text-green-800' 
                    : 'bg-red-100 text-red-800'
                ]"
              >
                {{ role.status === 'active' ? '启用' : '禁用' }}
              </span>
            </div>
            <div class="flex justify-between">
              <span class="text-sm font-medium text-gray-500">用户数量:</span>
              <span class="text-sm text-gray-900">{{ role.user_count }} 人</span>
            </div>
          </div>
          <div class="space-y-3">
            <div class="flex justify-between">
              <span class="text-sm font-medium text-gray-500">创建时间:</span>
              <span class="text-sm text-gray-900">{{ formatDate(role.created_at) }}</span>
            </div>
            <div class="flex justify-between">
              <span class="text-sm font-medium text-gray-500">更新时间:</span>
              <span class="text-sm text-gray-900">{{ formatDate(role.updated_at) }}</span>
            </div>
          </div>
        </div>
        
        <div class="mt-4">
          <span class="text-sm font-medium text-gray-500">角色描述:</span>
          <p class="mt-1 text-sm text-gray-900">{{ role.description }}</p>
        </div>
      </div>

      <!-- 权限列表 -->
      <div class="bg-gray-50 rounded-lg p-4">
        <h3 class="text-lg font-medium text-gray-900 mb-4">权限列表</h3>
        <div class="space-y-4">
          <div
            v-for="category in permissionCategories"
            :key="category"
            class="bg-white rounded-lg p-4 border"
          >
            <h4 class="text-md font-medium text-gray-800 mb-3 flex items-center">
              <i class="w-5 h-5 mr-2 text-blue-600 mdi:folder-outline" />
              {{ category }}
              <span class="ml-2 text-xs bg-blue-100 text-blue-800 px-2 py-1 rounded-full">
                {{ getCategoryPermissions(category).length }}
              </span>
            </h4>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
              <div
                v-for="permission in getCategoryPermissions(category)"
                :key="permission"
                class="flex items-center p-2 bg-gray-50 rounded-lg"
              >
                <i class="w-4 h-4 mr-2 text-green-500 mdi:check-circle" />
                <div>
                  <div class="text-sm font-medium text-gray-900">{{ permission }}</div>
                </div>
              </div>
            </div>
          </div>
          
          <div v-if="role.permissions.length === 0" class="text-center py-8">
            <i class="w-12 h-12 mx-auto text-gray-400 mdi:shield-off" />
            <p class="mt-2 text-sm text-gray-500">该角色暂无权限</p>
          </div>
        </div>
      </div>

      <!-- 关联用户 -->
      <div class="bg-gray-50 rounded-lg p-4">
        <h3 class="text-lg font-medium text-gray-900 mb-4">关联用户</h3>
        <div v-if="roleUsers.length > 0" class="space-y-3">
          <div
            v-for="user in roleUsers"
            :key="user.id"
            class="flex items-center justify-between p-3 bg-white rounded-lg border"
          >
            <div class="flex items-center">
              <img
                :src="user.avatar || `https://via.placeholder.com/32x32/3b82f6/ffffff?text=${user.username.charAt(0)}`"
                :alt="user.username"
                class="w-8 h-8 rounded-full"
              >
              <div class="ml-3">
                <div class="text-sm font-medium text-gray-900">{{ user.username }}</div>
                <div class="text-xs text-gray-500">{{ user.email }}</div>
              </div>
            </div>
            <div class="flex items-center space-x-2">
              <span
                :class="[
                  'inline-flex items-center px-2 py-1 rounded-full text-xs font-medium',
                  user.status === 'active' 
                    ? 'bg-green-100 text-green-800' 
                    : 'bg-red-100 text-red-800'
                ]"
              >
                {{ user.status === 'active' ? '激活' : '禁用' }}
              </span>
              <span class="text-xs text-gray-500">
                {{ formatDateTime(user.last_login) }}
              </span>
            </div>
          </div>
          
          <!-- 分页 -->
          <div v-if="totalUsers > roleUsers.length" class="text-center">
            <button
              @click="loadMoreUsers"
              :disabled="loadingUsers"
              class="btn-secondary"
            >
              <i v-if="loadingUsers" class="w-4 h-4 mr-2 animate-spin mdi:loading" />
              加载更多用户
            </button>
          </div>
        </div>
        
        <div v-else class="text-center py-8">
          <i class="w-12 h-12 mx-auto text-gray-400 mdi:account-off" />
          <p class="mt-2 text-sm text-gray-500">该角色下暂无用户</p>
        </div>
      </div>

      <!-- 操作历史 -->
      <div class="bg-gray-50 rounded-lg p-4">
        <h3 class="text-lg font-medium text-gray-900 mb-4">操作历史</h3>
        <div class="space-y-3">
          <div
            v-for="log in operationLogs"
            :key="log.id"
            class="flex items-start space-x-3 p-3 bg-white rounded-lg border"
          >
            <div
              :class="[
                'flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center',
                getLogIconClass(log.action)
              ]"
            >
              <i :class="getLogIcon(log.action)" class="w-4 h-4" />
            </div>
            <div class="flex-1 min-w-0">
              <p class="text-sm font-medium text-gray-900">
                {{ log.description }}
              </p>
              <div class="flex items-center mt-1 text-xs text-gray-500">
                <span>{{ log.operator }}</span>
                <span class="mx-2">•</span>
                <span>{{ formatDateTime(log.created_at) }}</span>
              </div>
            </div>
          </div>
          
          <div v-if="operationLogs.length === 0" class="text-center py-4">
            <i class="w-12 h-12 mx-auto text-gray-400 mdi:history" />
            <p class="mt-2 text-sm text-gray-500">暂无操作记录</p>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="flex justify-end">
        <button
          @click="$emit('close')"
          class="btn-secondary"
        >
          关闭
        </button>
      </div>
    </template>
  </Modal>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import Modal from '@/components/Modal.vue'

interface Role {
  id: string
  name: string
  description: string
  permissions: string[]
  status: 'active' | 'inactive'
  user_count: number
  created_at: string
  updated_at: string
}

interface User {
  id: string
  username: string
  email: string
  avatar?: string
  status: 'active' | 'inactive'
  last_login: string
}

interface OperationLog {
  id: string
  action: 'create' | 'update' | 'delete' | 'assign' | 'revoke'
  description: string
  operator: string
  created_at: string
}

interface Props {
  role: Role
}

const props = defineProps<Props>()
const emit = defineEmits<{
  close: []
}>()

const roleUsers = ref<User[]>([])
const operationLogs = ref<OperationLog[]>([])
const loadingUsers = ref(false)
const totalUsers = ref(0)

// 权限分类
const permissionCategories = computed(() => {
  // 模拟权限分类
  const categoryMap: Record<string, string[]> = {
    '用户管理': ['用户管理', '角色管理', '权限管理'],
    '系统管理': ['系统设置', '日志查看'],
    '数据管理': ['数据导出'],
    '个人中心': ['个人资料', '密码修改']
  }
  
  return Object.keys(categoryMap).filter(category => 
    categoryMap[category].some(permission => props.role.permissions.includes(permission))
  )
})

// 获取分类下的权限
const getCategoryPermissions = (category: string) => {
  const categoryMap: Record<string, string[]> = {
    '用户管理': ['用户管理', '角色管理', '权限管理'],
    '系统管理': ['系统设置', '日志查看'],
    '数据管理': ['数据导出'],
    '个人中心': ['个人资料', '密码修改']
  }
  
  return categoryMap[category]?.filter(permission => 
    props.role.permissions.includes(permission)
  ) || []
}

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString('zh-CN')
}

// 格式化日期时间
const formatDateTime = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

// 获取日志图标
const getLogIcon = (action: string) => {
  const iconMap = {
    create: 'mdi:plus-circle',
    update: 'mdi:pencil-circle',
    delete: 'mdi:delete-circle',
    assign: 'mdi:account-plus',
    revoke: 'mdi:account-minus'
  }
  return iconMap[action] || 'mdi:information'
}

// 获取日志图标样式
const getLogIconClass = (action: string) => {
  const classMap = {
    create: 'bg-green-100 text-green-600',
    update: 'bg-blue-100 text-blue-600',
    delete: 'bg-red-100 text-red-600',
    assign: 'bg-purple-100 text-purple-600',
    revoke: 'bg-orange-100 text-orange-600'
  }
  return classMap[action] || 'bg-gray-100 text-gray-600'
}

// 加载更多用户
const loadMoreUsers = async () => {
  loadingUsers.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟加载更多用户数据
    const moreUsers: User[] = [
      {
        id: '4',
        username: 'user4',
        email: 'user4@example.com',
        status: 'active',
        last_login: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString()
      }
    ]
    
    roleUsers.value.push(...moreUsers)
  } catch (error) {
    console.error('加载用户失败:', error)
  } finally {
    loadingUsers.value = false
  }
}

// 加载角色详细数据
const loadRoleDetails = async () => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟关联用户数据
    roleUsers.value = [
      {
        id: '1',
        username: 'admin',
        email: 'admin@example.com',
        status: 'active',
        last_login: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString()
      },
      {
        id: '2',
        username: 'user1',
        email: 'user1@example.com',
        status: 'active',
        last_login: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString()
      },
      {
        id: '3',
        username: 'user2',
        email: 'user2@example.com',
        status: 'inactive',
        last_login: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString()
      }
    ]
    
    totalUsers.value = props.role.user_count

    // 模拟操作日志
    operationLogs.value = [
      {
        id: '1',
        action: 'create',
        description: `创建了角色 "${props.role.name}"`,
        operator: 'admin',
        created_at: props.role.created_at
      },
      {
        id: '2',
        action: 'update',
        description: `更新了角色 "${props.role.name}" 的权限配置`,
        operator: 'admin',
        created_at: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString()
      },
      {
        id: '3',
        action: 'assign',
        description: `将用户 "user1" 分配到角色 "${props.role.name}"`,
        operator: 'admin',
        created_at: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString()
      }
    ]
  } catch (error) {
    console.error('加载角色详情失败:', error)
  }
}

onMounted(() => {
  loadRoleDetails()
})
</script>